<?php

class UserController extends BackEndController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array(
                'allow',
                'actions' => array('login', 'logout'),
                'users' => array('*'),
            ),
            array(
                'allow',
                'actions' => array('index', 'view', 'create', 'update', 'admin', 'delete', 'UpdatePassword', 'employee'),
                'users' => array('@'),
                'expression' => 'Yii::app()->user->isAdmin() == "true"',
            ),

            array(
                'allow',
                'actions' => array('changePassword'),
                'users' => array('@'),
            ),

            array('deny', // deny all User
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionCreate() {
        $model = new User;

        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            $model->password = md5($model->password);
            if ($model->save())
                $this->redirect(array('index'));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];

            if ($model->save())
                $this->redirect(array('index'));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
    }

    public function actionIndex() {
        $model = new User('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['User']))
            $model->attributes = $_GET['User'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function loadModel($id) {
        $model = User::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Do login using login page.
     * @throws CHttpException
     */
    public function actionLogin() {
        if (!defined('CRYPT_BLOWFISH') || !CRYPT_BLOWFISH)
            throw new CHttpException(500, "This application requires that PHP was compiled with Blowfish support for crypt().");
        if (!Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
        }

        $model = new LoginForm();

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            $model->password = md5($model->password);
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(HSUrl::backendDefaultUrl());
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionChangePassword() {
        $id = Yii::app()->user->id;
        $user = User::model()->findByPk($id);
        if (isset($_POST['User'])) {
            $user->attributes = $_POST['User'];
            $user->password = md5($user->password);

            $user->save();
            $this->redirect(HSUrl::backendDefaultUrl());
        }
        $this->render('changePassword', array('model' => new User()));

    }

    public function actionUpdatePassword($id) {
        $model = $this->loadModel($id);
        if (isset($_POST['User'])) {
            if ($_POST['User']['password'] != '') {
                $model->password = md5($_POST['User']['password']);
                $model->save();
                $this->redirect(HSUrl::backendDefaultUrl());
            }
        }
        $this->render('updatePassword', array('model' => $model));
    }

    public function  actionEmployee() {
        if (!isset($_GET['user_id'])) throw new CHttpException(999, 'Invalid request');

        $user = User::model()->findByPk($_GET['user_id']);
        if ($user == null) throw new CHttpException(999, 'Invalid request');

        $mo_tasks = Task::model()->findAll(array(
            'select' => '*',
            'condition' => '(user_id = 0 or user_id = :user_id) and (day like :day or day like :all)',
            'params' => array('user_id' => $user->id, 'day' => "%" . DayEnum::monday . "%", 'all' => '%' . DayEnum::all . '%')
        ));

        $tu_tasks = Task::model()->findAll(array(
            'select' => '*',
            'condition' => '(user_id = 0 or user_id = :user_id) and (day like :day or day like :all)',
            'params' => array('user_id' => $user->id, 'day' => "%" . DayEnum::tuesday . "%", 'all' => '%' . DayEnum::all . '%')
        ));

        $we_tasks = Task::model()->findAll(array(
            'select' => '*',
            'condition' => '(user_id = 0 or user_id = :user_id) and (day like :day or day like :all)',
            'params' => array('user_id' => $user->id, 'day' => "%" . DayEnum::wednesday . "%", 'all' => '%' . DayEnum::all . '%')
        ));

        $th_tasks = Task::model()->findAll(array(
            'select' => '*',
            'condition' => '(user_id = 0 or user_id = :user_id) and (day like :day or day like :all)',
            'params' => array('user_id' => $user->id, 'day' => "%" . DayEnum::thursday . "%", 'all' => '%' . DayEnum::all . '%')
        ));

        $fr_tasks = Task::model()->findAll(array(
            'select' => '*',
            'condition' => '(user_id = 0 or user_id = :user_id) and (day like :day or day like :all)',
            'params' => array('user_id' => $user->id, 'day' => "%" . DayEnum::friday . "%", 'all' => '%' . DayEnum::all . '%')
        ));

        $sa_tasks = Task::model()->findAll(array(
            'select' => '*',
            'condition' => '(user_id = 0 or user_id = :user_id) and (day like :day or day like :all)',
            'params' => array('user_id' => $user->id, 'day' => "%" . DayEnum::saturday . "%", 'all' => '%' . DayEnum::all . '%')
        ));

        $su_tasks = Task::model()->findAll(array(
            'select' => '*',
            'condition' => '(user_id = 0 or user_id = :user_id) and (day like :day or day like :all)',
            'params' => array('user_id' => $user->id, 'day' => "%" . DayEnum::sunday . "%", 'all' => '%' . DayEnum::all . '%')
        ));

        $this->render('detail', array(
            'mo_tasks' => $mo_tasks,
            'tu_tasks' => $tu_tasks,
            'we_tasks' => $we_tasks,
            'th_tasks' => $th_tasks,
            'fr_tasks' => $fr_tasks,
            'sa_tasks' => $sa_tasks,
            'su_tasks' => $su_tasks,
            'user' => $user
        ));

    }

}
